package com.bzkj.basicinfo.service.impl.ncc;


import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bzkj.basicinfo.domain.ncc.*;
import com.bzkj.basicinfo.mapper.NccBasicSkuMapper;
import com.bzkj.basicinfo.service.ncc.NccBasicSkuService;
import com.bzkj.basicinfo.utils.NccBasicUtil;
import com.bzkj.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

/**
 * 物料信息：1
 */
@Service("nccJobSkuService")
public class NccBasicSkuServiceImpl implements NccBasicSkuService {
    @Autowired
    private NccBasicSkuMapper nccBasicSkuMapper;

    @Value("${pk_org.code}")
    private Integer pkOrgCode;

    @Autowired
    private NccBasicUtil nccBasicUtil;
    @Value("${ncc.baseUrl}")
    private static String url;

    @Value("${ncc.basicInfoUrl}")
    private static String basicInfoUrl;

    @Value("${ncc.sourceSystem}")
    private static String sourceSystem;

    @Value("${ncc.targetSystem}")
    private static String targetSystem;

    @Value("${ncc.serviceName}")
    private static String serviceName;

    @Value("${ncc.contentType}")
    private static String contentType;

    /**
     * 根据code查询ncc商品信息
     *
     * @param code
     * @return
     */
    @Override
    public NccBasicSkuInfo selectNccInfoByCode(String code) {
        return nccBasicSkuMapper.queryNccBasicSkuInfo(code);
    }

    /**
     * 根据code查询ncc商品分类
     *
     * @param code
     * @return
     */
    @Override
    public NccBasicSkuType selectNccTypeByCode(String code) {
        return nccBasicSkuMapper.queryNccBasicSkuType(code);
    }

    /**
     * NCC商品信息定时任务
     */
    @Override
    public void updateNccBasicSkuInfoJob(String all) {
        if ("all".equals(all)) {
            nccBasicUtil.ncc(1, pkOrgCode);
        } else {
            HttpResponse response = methodExecute(1);

            if (response.isOk()) {
                String responseBody = response.body();
                JSONObject entries = JSONUtil.parseObj(responseBody);
                // 获取 data 数组
                JSONArray dataArray = entries.getJSONArray("data");
                // 将 JSONArray 转换为 List<NccBasicSkuInfoData>
                List<NccBasicSkuInfoData> skuInfoDataList = dataArray.toList(NccBasicSkuInfoData.class);

                if (!skuInfoDataList.isEmpty()) {
                    for (NccBasicSkuInfoData skuInfo : skuInfoDataList) {
                        NccBasicSkuInfo nccBasicSkuInfo = new NccBasicSkuInfo();
                        nccBasicSkuInfo.setPk_material(skuInfo.getpK_MATERIAL());
                        nccBasicSkuInfo.setCode(skuInfo.getCode());
                        nccBasicSkuInfo.setName(skuInfo.getName());
                        nccBasicSkuInfo.setMaterialshortname(skuInfo.getMaterialshortname());
                        nccBasicSkuInfo.setMaterialspec(skuInfo.getMaterialspec());
                        nccBasicSkuInfo.setMaterialmnecode(skuInfo.getMaterialmnecode());
                        nccBasicSkuInfo.setMaterialtype(skuInfo.getMaterialtype());
                        nccBasicSkuInfo.setPk_marbasclass(skuInfo.getpK_MARBASCLASS());
                        nccBasicSkuInfo.setPk_measdoc(skuInfo.getpK_MEASDOC());
                        nccBasicSkuInfo.setProdarea(skuInfo.getProdarea());
                        nccBasicSkuInfo.setManufactory(skuInfo.getManufactory());
                        nccBasicSkuInfo.setPk_org(skuInfo.getpK_ORG());
                        nccBasicSkuInfo.setPk_group(skuInfo.getpK_GROUP());
                        nccBasicSkuInfo.setPk_source(skuInfo.getpK_SOURCE());
                        nccBasicSkuInfo.setEnable_state(skuInfo.getEnablestate());
                        nccBasicSkuInfo.setCreator(skuInfo.getCreator());
                        nccBasicSkuInfo.setCreateTime(skuInfo.getCreationtime());
                        nccBasicSkuInfo.setModifier(skuInfo.getModifier());
                        nccBasicSkuInfo.setModifierTime(skuInfo.getModifiedtime());
                        nccBasicSkuInfo.setTsTime(skuInfo.getTs());
                        nccBasicSkuInfo.setDef1(skuInfo.getDeF1());
                        nccBasicSkuInfo.setDef2(skuInfo.getDeF2());
                        nccBasicSkuInfo.setDef3(skuInfo.getDeF3());
                        nccBasicSkuInfo.setDef4(skuInfo.getDeF4());
                        nccBasicSkuInfo.setDef5(skuInfo.getDeF5());

                        // 根据 code 查询数据库
//                        NccBasicSkuInfo queryNccBasicSkuInfo = nccBasicSkuMapper.queryNccBasicSkuInfo(skuInfo.getCode());
//                        if (queryNccBasicSkuInfo != null) {
//                            // 如果存在，更新数据
//                            nccBasicSkuMapper.updateNccBasicSkuInfo(nccBasicSkuInfo);
//                        } else {
//                            // 如果不存在，新增数据
//                            nccBasicSkuMapper.insertNccBasicSkuInfo(nccBasicSkuInfo);
//                            //创建动态表，只筛选启用状态的和pk_material不是产成品1001A11000000000D74G的数据才生成
//                            if ("2".equals(skuInfo.getEnablestate())&&!"1001A11000000000D74G".equals(skuInfo.getpK_MARBASCLASS()))
//                                nccBasicSkuMapper.createNccBasicSkuInfoTable("Table_" + skuInfo.getpK_MARBASCLASS() + "_sku");
//                            }



                        if ("1001A11000000000D74A".equals(skuInfo.getpK_MARBASCLASS())||
                                "1001A11000000000D74C".equals(skuInfo.getpK_MARBASCLASS())||
                                "1001ZZ100000000B63G4".equals(skuInfo.getpK_MARBASCLASS())||
                                "1001ZZ100000000B63G5".equals(skuInfo.getpK_MARBASCLASS())
                        ){
                                nccBasicSkuMapper.createNccBasicSkuInfoTable("Table_" + skuInfo.getpK_MATERIAL() + "_sku");
                            }
                    }
                }
            }
        }


    }

    /**
     * NCC商品分类定时任务
     */
    @Override
    public void updateNccBasicSkuTypeJob(String all) {
        if ("all".equals(all)) {
            nccBasicUtil.ncc(2, pkOrgCode);
        } else {
            HttpResponse response = methodExecute(2);

            if (response.isOk()) {
                String responseBody = response.body();
                JSONObject entries = JSONUtil.parseObj(responseBody);
                JSONArray dataArray = entries.getJSONArray("data");
                List<NccBasicSkuTypeData> skuTypeDataList = dataArray.toList(NccBasicSkuTypeData.class);
                for (NccBasicSkuTypeData nccBasicSkuTypeData : skuTypeDataList) {
                    NccBasicSkuType nccBasicSkuType = new NccBasicSkuType();
                    nccBasicSkuType.setNccStuCode(nccBasicSkuTypeData.getCode());
                    nccBasicSkuType.setNccStuName(nccBasicSkuTypeData.getName());
                    nccBasicSkuType.setPkMarbasclass(nccBasicSkuTypeData.getpK_MARBASCLASS());
                    nccBasicSkuType.setCreatetime(nccBasicSkuTypeData.getCreateTime());
                    nccBasicSkuType.setPkOrg(nccBasicSkuType.getPkOrg());
                    nccBasicSkuType.setPkGroup(nccBasicSkuType.getPkGroup());
                    nccBasicSkuType.setEnableState(nccBasicSkuType.getEnableState());
                    nccBasicSkuType.setTstime(nccBasicSkuTypeData.getTs());
                    nccBasicSkuType.setCreator(nccBasicSkuTypeData.getCreator());
                    nccBasicSkuType.setDef1(nccBasicSkuTypeData.getDeF1());
                    nccBasicSkuType.setDef2(nccBasicSkuTypeData.getDeF2());
                    nccBasicSkuType.setDef3(nccBasicSkuTypeData.getDeF3());
                    nccBasicSkuType.setDef4(nccBasicSkuTypeData.getDeF4());
                    nccBasicSkuType.setDef5(nccBasicSkuTypeData.getDeF5());

                    NccBasicSkuType nccBasicSkuType1 = nccBasicSkuMapper.queryNccBasicSkuType(nccBasicSkuTypeData.getCode());
                    if (nccBasicSkuType1 != null) {
                        // 如果存在，更新数据
                        nccBasicSkuMapper.updateNccBasicSkuType(nccBasicSkuType);
                    } else {
                        // 如果不存在，新增数据
                        nccBasicSkuMapper.insertNccBasicSkuType(nccBasicSkuType);
                    }
                }

            }
        }
    }

    /**
     * NCC物料单位定时任务
     */
    @Override
    public void updateNccBasicDepartmentJob(String all) {
        if ("all".equals(all)) {
            nccBasicUtil.ncc(3, pkOrgCode);
        } else {
            HttpResponse response = methodExecute(3);
            if (response.isOk()) {
                String responseBody = response.body();
                JSONObject entries = JSONUtil.parseObj(responseBody);
                JSONArray dataArray = entries.getJSONArray("data");
                List<NccBasicDepartment> nccBasicDepartments = dataArray.toList(NccBasicDepartment.class);
                for (NccBasicDepartment basicDepartment : nccBasicDepartments) {
                    NccBasicDepartment basicDepartment1 = nccBasicSkuMapper.queryNccBasicDepartment(basicDepartment.getCode());
                    if (basicDepartment1 != null) {
                        nccBasicSkuMapper.updateNccBasicDepartment(basicDepartment);
                    } else {
                        nccBasicSkuMapper.insertNccBasicDepartment(basicDepartment);
                    }
                }
            }
        }
    }

    /**
     * NCC物料换算系数定时任务
     */
    @Override
    public void updateNccBasicReducedUnitJob(String all) {
        if ("all".equals(all)) {
            nccBasicUtil.ncc(4, pkOrgCode);
        } else {
            HttpResponse response = methodExecute(4);
            if (response.isOk()) {
                String responseBody = response.body();
                JSONObject entries = JSONUtil.parseObj(responseBody);
                JSONArray dataArray = entries.getJSONArray("data");
                List<NccBasicReducedUnit> nccBasicReducedUnits = dataArray.toList(NccBasicReducedUnit.class);
                for (NccBasicReducedUnit reducedUnit : nccBasicReducedUnits) {
                    NccBasicReducedUnit reducedUnit1 = nccBasicSkuMapper.queryNccBasicReducedUnit(reducedUnit.getpK_MATERIAL());
                    if (reducedUnit1 != null) {
                        nccBasicSkuMapper.updateNccBasicReducedUnit(reducedUnit);
                    } else {
                        nccBasicSkuMapper.insertNccBasicReducedUnit(reducedUnit);
                    }
                }
            }
        }
    }

    @Override
    public AjaxResult getNccInfoAll() {
        List<HashMap> hashMaps = nccBasicSkuMapper.queryNccBasicSkuTypeAll();
        return AjaxResult.success(hashMaps);
    }


    /**
     * 公有方法抽取
     *
     * @param i
     * @return
     */
    public HttpResponse methodExecute(Integer i) {
        //        String url = NccHttpUtils.getUrl();
        HashMap<String, Object> hashMap = new HashMap<>();
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取昨天的日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        // 昨天的00:00
        LocalDateTime startOfYesterday = yesterday.atStartOfDay();
        String startOfYesterdayStr = startOfYesterday.format(formatter);
        // 昨天的23:59:59
        LocalDateTime endOfYesterday = yesterday.atTime(23, 59, 59);
        String endOfYesterdayStr = endOfYesterday.format(formatter);
//        添加post请求参数
        hashMap.put("startTime", startOfYesterdayStr);

//        hashMap.put("startTime", "2022-01-01 02:32:20");
        hashMap.put("endTime", endOfYesterdayStr);
        hashMap.put("nccBaseDataEnum", i);
        hashMap.put("platformCode", "111");
        String jsonString = JSONUtil.toJsonStr(hashMap);

        // 添加请求头
        HttpResponse response = HttpUtil.createPost(basicInfoUrl)
                .header("sourceSystem", sourceSystem)
                .header("targetSystem", targetSystem)
                .header("serviceName", serviceName)
                .header("contentType",contentType)
                .body(jsonString, "application/json")
                .execute();
        return response;
    }
}
